package com.baor.filter;

import com.baor.base.config.TokenService;
import com.baor.base.domain.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;


@Component
public class JwtAuthenticationFilter implements WebFilter {

    @Autowired
    private TokenService tokenService;

    public String resovleToken(ServerHttpRequest request){
        String token = request.getHeaders().getFirst("token");
        if(token != null && token.length() == 0)
            return null;
        return token;

    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = resovleToken(request);
        String uri = request.getURI().toString();
        return chain.filter(exchange);
//        if(uri.contains("login")){
//            return chain.filter(exchange);
//        }
//        if(token != null){
//            //验证token有效性  是否过期
//            System.out.println("token"+this.tokenService);
//            if(tokenService.isExpired(token)){
//                //TODO  token 存在并有效
//                UserVO userInfo = this.tokenService.getUserInfo(token);
//                Authentication authentication = new UsernamePasswordAuthenticationToken(userInfo.getUserName(),userInfo.getUserPassword(),null);
//                if(authentication != null){
//                    return chain.filter(exchange).contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication));
//                }
//            }else{
//                throw new RuntimeException("token已过期");
//            }
//        }
//        return chain.filter(exchange);
    }
}
